package com.nineclock.document.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.nineclock.common.entity.UserInfo;
import com.nineclock.common.filter.CurrentUserHolder;
import com.nineclock.common.utils.BeanHelper;
import com.nineclock.document.dto.DocFileDto;
import com.nineclock.document.dto.DocFolderDto;
import com.nineclock.document.dto.DocUserCollaborationDTO;
import com.nineclock.document.dto.DocumentDto;
import com.nineclock.document.enums.DocumentPermissionEnum;
import com.nineclock.document.mapper.DocCollaborationsMapper;
import com.nineclock.document.mapper.DocFileMapper;
import com.nineclock.document.mapper.DocFolderMapper;
import com.nineclock.document.pojo.DocCollaborations;
import com.nineclock.document.pojo.DocFile;
import com.nineclock.document.pojo.DocFolder;
import com.nineclock.document.service.DocFileService;
import com.nineclock.system.dto.SysCompanyUserDTO;
import com.nineclock.system.feign.SysCompanyUserFeign;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

@Service
@Transactional
public class DocFileServiceImpl implements DocFileService {

    @Autowired
    private DocFolderMapper folderMapper;

    @Autowired
    private DocFileMapper fileMapper;

    @Autowired
    private SysCompanyUserFeign companyUserFeign;

    @Autowired
    private DocCollaborationsMapper collaborationsMapper;


    @Override
    public DocumentDto queryFolderAndFile(Long parentFoldId) {

        // 查询符合条件的文件夹列表
        List<DocFolderDto> folders = queryFolders(parentFoldId);

        // 查询符合条件的文件列表
        List<DocFileDto> files = queryFiles(parentFoldId);

        // 封装数据
        DocumentDto documentDto = new DocumentDto();
        documentDto.setFiles(files);
        documentDto.setFolders(folders);

        return documentDto;
    }


    /**
     * 查询符合条件的文件列表
     * @param parentFoldId
     * @return
     */
    private List<DocFileDto> queryFiles(Long parentFoldId) {

        List<DocFile> fileList = new ArrayList<>();

        // 1.当前目录下，公共读/公共读写 的文件
        LambdaQueryWrapper<DocFile> wrapper1 = new LambdaQueryWrapper<>();
        wrapper1.eq(DocFile::getCompanyId, CurrentUserHolder.get().getCompanyId());
        wrapper1.eq(DocFile::getFolderId, parentFoldId);
        wrapper1.eq(DocFile::getStatus, 1);
        wrapper1.in(DocFile::getPermission, DocumentPermissionEnum.ALL_READ.getPermission(),
                DocumentPermissionEnum.ALL_READ_WRITE.getPermission());

        List<DocFile> fileList1 = fileMapper.selectList(wrapper1);
        if (!CollectionUtils.isEmpty(fileList1)) {
            fileList.addAll(fileList1);
        }

        // B.当前目录下，当前用户私有的文件
        LambdaQueryWrapper<DocFile> wrapper2 = new LambdaQueryWrapper<>();
        wrapper2.eq(DocFile::getCompanyId, CurrentUserHolder.get().getCompanyId());
        wrapper2.eq(DocFile::getFolderId, parentFoldId);
        wrapper2.eq(DocFile::getStatus, 1);
        wrapper2.eq(DocFile::getPermission, DocumentPermissionEnum.PRIVATE_READ_WRITE.getPermission());
        // 创建人id等于当前登录用户的员工id
        wrapper2.eq(DocFile::getCreateUserId, CurrentUserHolder.get().getCompanyUserId());

        List<DocFile> fileList2 = fileMapper.selectList(wrapper2);
        if (!CollectionUtils.isEmpty(fileList2)) {
            fileList.addAll(fileList2);
        }


        // C.当前目录下，当前用户是协作者的文件
        List<DocFile> fileList3 = fileMapper.selectFileListByCollaboration(CurrentUserHolder.get().getCompanyId(),
                parentFoldId, CurrentUserHolder.get().getCompanyUserId());

        if (!CollectionUtils.isEmpty(fileList3)) {
            fileList.addAll(fileList3);
        }

        // 文件去重，例如某些文件既是公共读，当前用户又是协作者
        HashSet<DocFile> fileHashSet = new HashSet<>(fileList);

        // 数据转换
        Set<DocFileDto> docFileDtos = BeanHelper.copyWithCollection(fileHashSet, DocFileDto.class);

        List<DocFileDto> docFileDtoList = docFileDtos.stream().map(docFileDto -> {

            // 调用系统微服务Feign接口根据更新人员工id，查询更新人员工信息
            SysCompanyUserDTO updateUserDTO = companyUserFeign.queryCompanyUserById(docFileDto.getUpdateUserId()).getData();
            if (updateUserDTO != null) {
                docFileDto.setUpdateUserName(updateUserDTO.getUserName());
            }

            // 调用系统微服务Feign接口根据创建人员工id，查询创建人员工信息
            SysCompanyUserDTO createUserDTO = companyUserFeign.queryCompanyUserById(docFileDto.getCreateUserId()).getData();
            if (createUserDTO != null) {
                docFileDto.setUserName(createUserDTO.getUserName());
            }

            return docFileDto;

        }).collect(Collectors.toList());

        return docFileDtoList;

    }

    /**
     * 查询符合条件的文件夹列表
     * @return
     */
    private List<DocFolderDto> queryFolders(Long parentFoldId) {
        LambdaQueryWrapper<DocFolder> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(DocFolder::getCompanyId, CurrentUserHolder.get().getCompanyId());
        wrapper.eq(DocFolder::getParentId, parentFoldId);
        wrapper.eq(DocFolder::getStatus, 1);

        List<DocFolder> docFolders = folderMapper.selectList(wrapper);

        if (!CollectionUtils.isEmpty(docFolders)) {
            return BeanHelper.copyWithCollection(docFolders, DocFolderDto.class);
        }
        return null;
    }

    @Override
    public DocFileDto getFileByFileId(Long id) {
        DocFile docFile = fileMapper.selectById(id);
        return BeanHelper.copyProperties(docFile, DocFileDto.class);
    }

    @Override
    public List<DocUserCollaborationDTO> queryUsers(Long id) {

        // 调用系统微服务查询当前企业员工列表
        List<SysCompanyUserDTO> companyUserDTOS = companyUserFeign.queryAllCompanyUser().getData();

        // 根据文件id查询文件
        DocFile docFile = fileMapper.selectById(id);

        // 根据文件id查询协作者id集合
        LambdaQueryWrapper<DocCollaborations> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(DocCollaborations::getFileId, id);
        List<DocCollaborations> collaborationsList = collaborationsMapper.selectList(wrapper);

        // 获取协作者id集合
        List<Long> companyUserIdList = collaborationsList.stream().map(docCollaborations -> {
            return docCollaborations.getCollaborationId();
        }).collect(Collectors.toList());


        // 数据转换，将员工DTO转为DocUserCollaborationDTO
        List<DocUserCollaborationDTO> docUserCollaborationDTOS = companyUserDTOS.stream().map(sysCompanyUserDTO -> {

            DocUserCollaborationDTO docUserCollaborationDTO = new DocUserCollaborationDTO();
            docUserCollaborationDTO.setId(sysCompanyUserDTO.getId());
            docUserCollaborationDTO.setUsername(sysCompanyUserDTO.getUserName());
            docUserCollaborationDTO.setImgUrl(sysCompanyUserDTO.getImageUrl());
            docUserCollaborationDTO.setPhone(sysCompanyUserDTO.getMobile());

            if(docFile.getCreateUserId() == sysCompanyUserDTO.getId()){
                docUserCollaborationDTO.setState(1); // 拥有者
            }else if(companyUserIdList.contains(sysCompanyUserDTO.getId())){
                docUserCollaborationDTO.setState(2); // 协作者
            }else{
                docUserCollaborationDTO.setState(0);
            }

            return docUserCollaborationDTO;

        }).collect(Collectors.toList());

        return docUserCollaborationDTOS;
    }

}
